import 'dart:async';
import 'dart:io';

import 'package:applications/database/local_db.dart';
import 'package:applications/module/home/home_page.dart';
import 'package:applications/utils/provider_logger.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  setCustomErrorPage();
  _setTargetPlatformForDesktop();

  FlutterError.onError = (FlutterErrorDetails details) async {
    if (details.stack != null) {
      Zone.current.handleUncaughtError(details.exception, details.stack!);
    }
  };
  runZonedGuarded(() {
    /// 强制竖屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitDown,
      DeviceOrientation.portraitUp,
    ]).then((_) async {
      await LocalDb.instance.initDb();
      runApp(
        ProviderScope(
          observers: [ProviderLogger()],
          child: const MyApp(),
        ),
      );
      //异常上报
      // Android设备透明状态栏
      if (Platform.isAndroid) {
        // 以下两行 设置android状态栏为透明的沉浸。写在组件渲染之后，是为了在渲染后进行set赋值，覆盖状态栏，写在渲染之前MaterialApp组件会覆盖掉这个值。
        SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
        );
        SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
      }
    });
  }, (Object error, StackTrace stack) {
    //zone内异常handle直接上报
    debugPrint("Main方法拦截的异常 ${error.toString()}");
    debugPrint(stack.toString());
  });
}

void setCustomErrorPage() {
  ErrorWidget.builder = (FlutterErrorDetails flutterErrorDetails) {
    debugPrint(flutterErrorDetails.toString());
    return const Center(child: Text("系统异常，请前往反馈！"));
  };
}

/// If the current platform is desktop, override the default platform to
/// a supported platform (iOS for macOS, Android for Linux and Windows).
/// Otherwise, do nothing.
void _setTargetPlatformForDesktop() {
  TargetPlatform? targetPlatform;
  if (Platform.isMacOS) {
    targetPlatform = TargetPlatform.iOS;
  } else if (Platform.isLinux || Platform.isWindows) {
    targetPlatform = TargetPlatform.android;
  }
  if (targetPlatform != null) {
    debugDefaultTargetPlatformOverride = targetPlatform;
  }
}

class MyApp extends StatelessWidget {
  final Widget? home;

  const MyApp({Key? key, this.home}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      // 设计稿按iPhone6的尺寸设计的(iPhone6 750*1334)
      designSize: const Size(750, 1334),
      // allowFontScaling: false,
      builder: (context, child) => MaterialApp(
        title: '热门App',
        // 右上角显示一个debug的图标
        debugShowCheckedModeBanner: false,
        // showPerformanceOverlay: true, //显示性能标签
        // checkerboardRasterCacheImages: true,
        // showSemanticsDebugger: true, // 显示语义视图
        // checkerboardOffscreenLayers: true, // 检查离屏渲染
        theme: ThemeData(
          primarySwatch: Colors.blue,
          scaffoldBackgroundColor: Colors.white,
        ),
        builder: (context, widget) {
          return MediaQuery(
            /// Setting font does not change with system font size
            data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
            child: widget ?? const SizedBox.shrink(),
          );
        },
        home: home ?? const HomePage(),
      ),
    );
  }
}
